﻿//------------------------------------------------------------------------------
// <pcdd-entitiy>
//     彩票主流业务类库
//     微信支付业务对象
// </pcdd-entitiy>
//------------------------------------------------------------------------------

using CL.Enum.Common;
using CL.Game.Entity;
using CL.Json.Entity.WebAPI;
using CL.Tools.Common;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using ThoughtWorks.QRCode.Codec;

namespace CL.Game.BLL.PayInterface
{
    /// <summary>
    /// WeChatPay 业务
    /// </summary>
    public class WeChatPay
    {
        /// <summary>
        /// 验证订单号是否已存在数据库
        /// </summary>
        /// <returns></returns>
        private string GetNotbout_trade_no()
        {
            string tbout_trade_no = WFTPayHelper.Nmrandom();
            bool result = new UsersPayDetailBLL().IsTboutTradeNo(tbout_trade_no);
            if (result)
                return tbout_trade_no;
            else
                return GetNotbout_trade_no();
        }


        /// <summary>
        /// 微信支付二维码url生成
        /// 接口调用
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="Amount"></param>
        /// <param name="IpAddress"></param>
        /// <param name="tbBody"></param>
        /// <param name="tbAttach"></param>
        /// <returns></returns>
        public PreparePaymentResult WeChatPrepayment(long UserCode, int Amount, string tbBody, string tbAttach)
        {
            int RecCode = (int)ResultCode.Success;
            string WeChatLink = string.Empty;
            string Out_Trade_No = string.Empty;
            try
            {
                WeChatPayHelper helper = new WeChatPayHelper();
                string IpAddress = string.Empty;
                try
                {
                    IpAddress = Utils.RequestIP;
                    if (!Utils.IsIP(IpAddress))
                        IpAddress = "127.0.0.1";
                }
                catch
                {
                    IpAddress = "127.0.0.1";
                }
                Out_Trade_No = this.GetNotbout_trade_no();

                UsersPayDetailEntity entity = new UsersPayDetailEntity()
                {
                    RechargeNo = "0",
                    Amount = Amount,
                    CreateTime = DateTime.Now,
                    FormalitiesFees = 0,
                    OrderNo = Out_Trade_No,
                    PayType = "WeChatPay",
                    Result = 0,
                    UserID = UserCode,
                    OutRechargeNo = "0"
                };
                long id = new UsersPayDetailBLL().InsertEntity(entity);
                if (id > 0)
                    WeChatLink = SaveQRCodeImg(UserCode, helper.GetPayUrl(id.ToString(), Out_Trade_No, Amount, tbBody, tbAttach, IpAddress));
                else
                    RecCode = (int)ResultCode.PayDetailsFailure;
            }
            catch (Exception ex)
            {
                new Log("WeChatPay").Write(string.Format("微信支付二维码url生成错误：{0}", ex.Message), true);
                RecCode = (int)ResultCode.Error;
                WeChatLink = string.Empty;
                Out_Trade_No = string.Empty;
            }
            return new PreparePaymentResult()
            {
                Code = RecCode,
                Msg = Common.GetDescription((ResultCode)RecCode),
                Data = new PreparePaymentEnttiy_WFT()
                {
                    OrderNo = Out_Trade_No,
                    TokenID = string.Empty,
                    PayLink = WeChatLink
                }
            };
        }
        /// <summary>
        /// 二维码
        /// </summary>
        /// <returns></returns>
        protected string SaveQRCodeImg(long UserCode, string PayUrl)
        {
            string QRCodeImgPath = string.Empty;
            if (!string.IsNullOrEmpty(PayUrl))
            {
                try
                {
                    string ImgName = string.Format("wechatqrcode_{0}.jpg", Utils.MD5(UserCode.ToString()).Substring(0, 16).ToLower());
                    string PathName = string.Format("QRCodeImg");
                    string SavePath = string.Format("{0}\\{1}", (System.Configuration.ConfigurationManager.AppSettings["ICON"] ?? "").TrimEnd('\\'), PathName);
                    QRCodeImgPath = string.Format("{0}/{1}/{2}", (System.Configuration.ConfigurationManager.AppSettings["ICONHOSTURL"] ?? "").TrimEnd('/'), PathName, ImgName);
                    //如果保存目录不存在，则创建
                    if (!Directory.Exists(SavePath))
                        Directory.CreateDirectory(SavePath);
                    SavePath = string.Format("{0}\\{1}", SavePath, ImgName);
                    //添加时如果图片已经存在则删除
                    if (File.Exists(SavePath))
                        File.Delete(SavePath);

                    //初始化二维码生成工具
                    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    qrCodeEncoder.QRCodeVersion = 0;
                    qrCodeEncoder.QRCodeScale = 10;
                    //将字符串生成二维码图片
                    Bitmap image = qrCodeEncoder.Encode(PayUrl, Encoding.Default);
                    MemoryStream ms = new MemoryStream();
                    image.Save(SavePath, ImageFormat.Jpeg);
                    ms.Close();
                }
                catch (Exception ex)
                {
                    QRCodeImgPath = string.Empty;
                    new Log("SaveQRCodeImg").Write(string.Format("二维码图片保存失败错误：{0}", ex.Message), true);
                }
            }
            return QRCodeImgPath;
        }

    }
}
